package jrain.utils.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

import jrain.utils.consts.BaseConst;
import jrain.utils.exception.ServiceException;
import jrain.utils.io.IoConsumer;
import jrain.utils.url.UrlUtils;

/**
 * <pre>
 * 作者：3244924214@qq.com 
 * 描述： 文件工具类
 * </pre>
 */
public class FileUtils {

	/**
	 * 写文件
	 * @param home 根路径
	 * @param path 路径
	 * @param content 文件
	 */
	public static void writeFile(String home, String path, String content) {
		writeFile(home, path, w -> w.write(content));
	}

	/**
	 * 写文件
	 * @param home 根路径
	 * @param path 路径
	 * @param consumer 自定义函数
	 */
	public static void writeFile(String home, String path, IoConsumer<Writer> consumer) {
		String filePath = UrlUtils.joinUrl(home, path);
		File file = new File(filePath);
		File pfile = file.getParentFile();
		if (pfile != null) {
			pfile.mkdirs();
		}
		OutputStreamWriter fileWriter = null;
		try {
			fileWriter = new OutputStreamWriter(new FileOutputStream(file), BaseConst.UTF8);
			consumer.accept(fileWriter);
			fileWriter.flush();
		} catch (Exception e) {
			throw new ServiceException(e.getMessage(), e);
		} finally {
			try {
				fileWriter.close();
			} catch (IOException e) {
			}
		}
	}

	public static String getFileExt(String fileName) {
		return "." + getFileExtName(fileName);
	}

	public static String getFileExtName(String fileName) {
		if (fileName == null || fileName.length() == 0) {
			return "";
		}
		String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
		if ("gz".equals(ext) && fileName.endsWith(".tar.gz")) {
			ext = "tar.gz";
		} else if ("xz".equals(ext) && fileName.endsWith(".tar.xz")) {
			ext = "tar.xz";
		} else if ("bz2".equals(ext) && fileName.endsWith(".tar.bz2")) {
			ext = "tar.bz2";
		}
		return ext;
	}
}
